package com.william.jdbcplus.core.ds;

import com.alibaba.druid.pool.DruidDataSource;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class PlusDataSourceImpl implements PlusDataSource {
    /**
     * 随机获取slave库的索引
     */
    private AtomicInteger roundIndex = new AtomicInteger(-1);

    /**
     * 主库 （ 写 库 ）
     */
    private DruidDataSource master;

    /**
     * 从库 （ 读 库 ）
     */
    private List<DruidDataSource> slaves;

    /**
     * 是否存在 从库（ 读 库 ）
     */
    private boolean existSlave;

    private PlusDataSourceImpl() {

    }

    public PlusDataSourceImpl(DruidDataSource master, List<DruidDataSource> slaves) {
        this.master = master;
        this.slaves = slaves;
        this.existSlave = slaves == null || slaves.isEmpty() ? false : true;
    }

    @Override
    public DruidDataSource getMaster() {
        return master;
    }

    @Override
    public List<DruidDataSource> getSlaves() {
        return slaves;
    }

    @Override
    public DruidDataSource getQueryNode() {
        if (this.existSlave) {
            int round = this.roundIndex.incrementAndGet();
            // 避免 roundIndex 越界错误
            if (round < 0) {
                this.roundIndex = new AtomicInteger(-1);
                round = this.roundIndex.incrementAndGet();
            }
            return this.slaves.get(Math.abs(round % this.slaves.size()));
        } else {
            return this.master;
        }
    }
}
